package com.iteaj.network.codec;

import com.iteaj.network.AbstractMessage;
import com.iteaj.network.ProtocolException;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import org.springframework.beans.BeanUtils;

/**
 * 报文{@link AbstractMessage}解码器
 * 使用此解码器务必保留默认的报文构造函数{@link AbstractMessage#AbstractMessage(byte[])}
 */
public interface IotMessageDecoder extends ChannelInboundHandler {

    Class<? extends AbstractMessage> getMessageClass();

    IotMessageDecoder setMessageClass(Class<? extends AbstractMessage> messageClass);

    /**
     * 使用默认的构造函数 {@link AbstractMessage#AbstractMessage(byte[])} 构造实体报文
     * @param ctx
     * @param decode 可以是类型 ByteBuf、AbstractMessage、null
     * @return AbstractMessage 使用默认的构造函数 {@link AbstractMessage#AbstractMessage(byte[])}
     * @throws Exception
     */
    default AbstractMessage proxy(ChannelHandlerContext ctx, Object decode) throws Exception {
        if(decode instanceof ByteBuf) {
            int readableBytes = ((ByteBuf) decode).readableBytes();
            byte[] message = new byte[readableBytes];
            ((ByteBuf) decode).readBytes(message);

            // 报文必须保留默认的构造函数
            return BeanUtils.instantiateClass(getMessageClass().getConstructor(byte[].class), message).build();
        } else if(decode instanceof AbstractMessage) {
            return ((AbstractMessage) decode).build();
        } else if(decode == null) {
            return null;
        } else {
            throw new ProtocolException("解码错误");
        }
    }
}
